package org.liaohailong.library.widget.photoview.guesture;

import android.view.MotionEvent;

import androidx.annotation.NonNull;

/**
 * create by liaohailong
 * time 2023/1/9 16:24
 * desc: 简单处理缩放手势
 */
public class VScaleGestureDetector {


    private Callback callback;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    private double lastLength;

    public void onTouchEvent(@NonNull MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_POINTER_DOWN: {
                if (event.getPointerCount() >= 2) {
                    float x0 = event.getX(0);
                    float y0 = event.getY(0);
                    float x1 = event.getX(1);
                    float y1 = event.getY(1);

                    float dx = x1 - x0;
                    float dy = y1 - y0;

                    // 负负得正，不用管dx dy是否有符号，勾股定理求两点距离
                    lastLength = Math.sqrt(dx * dx + dy * dy);
                }
            }
            break;

            case MotionEvent.ACTION_MOVE: {
                if (event.getPointerCount() >= 2) {
                    float x0 = event.getX(0);
                    float y0 = event.getY(0);
                    float x1 = event.getX(1);
                    float y1 = event.getY(1);

                    float dx = x1 - x0;
                    float dy = y1 - y0;

                    // 负负得正，不用管dx dy是否有符号，勾股定理求两点距离
                    double length = Math.sqrt(dx * dx + dy * dy);
                    float scale = (float) (length / lastLength);

                    float cx = (x1 + x0) / 2;
                    float cy = (y1 + y0) / 2;

                    if (callback != null) {
                        callback.onScale(scale, cx, cy);
                    }

                    lastLength = length;
                }
            }
            break;
        }
    }


    public interface Callback {
        /**
         * @param scale 缩放值，每次基于上一次ACTION_MOVE事件计算
         * @param cx    缩放中心点x坐标
         * @param cy    缩放中心点y坐标
         */
        void onScale(float scale, float cx, float cy);
    }
}
